<?php
/**
 * Created by PhpStorm.
 * function: 处理第三方登录：微信登录
 * User: yule
 * Date: 2016/4/29 0029
 * Time: 下午 6:48
 */

namespace Member\Controller;

use Common\Controller\UController;
use Common\Service\User\MemberService;
use Common\Service\User\UserService;

class LoginApiController extends UController
{
    private $_appId;
    private $_appSecret;
    private $_webRoot;
    private $_openUrlQrc;
    private $_openUrlToken;
    private $_openUrlUserInfo;
    public function __construct()
    {
		//修改成自己的
        $this->_appId = 'wxc123123123123132';//开放平台网站应用
        $this->_appSecret = 'fdksahfkuhuefheukfhkue';
        $this->_webRoot = 'http://course.aaaa.com/Member/LoginApi/wxCheck';//返回的域名网址，必须跟网站应用的域名网址相同
		
        $this->_openUrlQrc = 'https://open.weixin.qq.com/connect/qrconnect';//申请二维码接口
        $this->_openUrlToken = 'https://api.weixin.qq.com/sns/oauth2/access_token';//申请token接口
        $this->_openUrlUserInfo = 'https://api.weixin.qq.com/sns/userinfo';//申请用户信息接口
    }

    public function index(){

    }

    /**
     * 验证微信扫码后的用户数据
     */
    public function wxCheck(){
        $code = I('code');//只能使用1次即销毁
        $state = I('state');
        if($state != $_SESSION['wx_state']){
            $this->error("请进入官网扫描二维码",'/Member/LoginApi/wxLogin');
            exit();
        }
        session('wx_state',null);//清除这个session

        //获取access_token和openid信息，还有用户唯一标识unionid
        $ken = $this->wxToken($code);//:access_token,expires_in,refresh_token,openid,scope,unionid
        
        if($ken['errcode'] == 40029){
            $this->error("code参数已经过期");
        }

		//判断是否已存在
        $map = array(
            'openid' => $ken['openid'],
            'unionid' => $ken['unionid'];
        );
        $Member = new MemberService();//这个自己写一下查询数据库
        $res = $Member->getMemberInfo($map);//查询openid是否存在，而PC和微信端 openid不一致，只有unionid才是唯一标识
        if($res){

            $userinfo = Array(
                'uid' => $res['id'],
                'username' => $res['username'],
                'nickname' => $res['nickname'],
                'avatar' => $res['avatar'],
                'cellphone' => $res['cellphone'],
                'city' => $res['city'],
                'openid' => $res['openid'],

            );

        }
        else{
            $user = $this->wxUserInfo($ken['access_token'],$ken['openid']);//获取用户信息
            $data = array(
                'openid' => $user['openid'],
                'unionid' => $user['unionid'],
                'nickname' => $user['nickname'],
                'avatar' => $user['headimgurl'],
                'updated' => time(),
                'created' => time(),
            );
            $crId = $Member->addMember($data);//写入到数据库中,返回的是插入id
            $userinfo = Array(
                'uid' => $crId,
                'nickname' => $user['nickname'],
                'avatar' => $user['headimgurl'],
                'openid' => $user['openid'],

            );
        }
        session('userInfo', $userinfo);//写入session

    }

    /**
     * 提交微信登录请求
     */
    public function wxLogin(){
        $stats = $this->getRandChar(16);//该参数可用于防止csrf攻击（跨站请求伪造攻击）
        session('wx_state',$stats);//把随机字符串写入session，验证时对比
        $url = $this->_openUrlQrc.'?appid='.$this->_appId.'&redirect_uri='.urlencode($this->_webRoot).'&response_type=code&scope=snsapi_login&state='.$stats;
        redirect($url);//跳转到扫码
    }

    //生成随机数,length长度
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    //CURL获取url返回值
    function httpGet($url){
        $oCurl = curl_init();//实例化
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );//是否返回值，1时给字符串，0输出到屏幕
        $sContent = curl_exec($oCurl);//获得页面数据
        $aStatus = curl_getinfo($oCurl);//获取CURL连接数据的信息
        curl_close($oCurl);//关闭资源
        //获取成功
        $output_array = json_decode($sContent,true);//转换json格式
        if(intval($aStatus["http_code"])==200){
            return $output_array;
        }else{
            return false;
        }
    }

    //获取token信息
    public function wxToken($code){
        $url = $this->_openUrlToken.'?appid='.$this->_appId.'&secret='.$this->_appSecret.'&code='.$code.'&grant_type=authorization_code';
        $sContent = $this->httpGet($url);//获取token数据
//        dump($sContent);
        return $sContent;
    }
    //延长token时间,默认token两个小时
    public function wxrefresh($refresh){

        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$this->_appId.'&grant_type=refresh_token&refresh_token='.$refresh;
        return $this->httpGet($url);
    }

    //检验token授权是否有效
    public function wxchecktoken($token,$openid){
//        $token = 'OezXcEiiBSKSxW0eoylIeB1YmSEMVVx-QnR-TQB0UGhwGvDVZSksJNuoEXUlc2BYPQ7omt_iutprcPBjR4UjI3oEA5Z0k-N7yOOLn3h8AIF0-UhysqN3WjZAr-rHGVkWmPVh2FS9s-bUcL7Il1q7IQ';
//        $openid = 'o5ZGIxPWrZBa61964QTRGkSWyUgo';
        $url = 'https://api.weixin.qq.com/sns/auth?access_token='.$token.'&openid='.$openid;
        return $this->httpGet($url);
    }
    //获取微信用户个人信息，但公众号和开放平台opendid 会不一样，unionid是用户唯一标识
    public function wxUserInfo($token,$openid){
//        $token = 'OezXcEiiBSKSxW0eoylIeB1YmSEMVVx-QnR-TQB0UGhwGvDVZSksJNuoEXUlc2BYPQ7omt_iutprcPBjR4UjI3oEA5Z0k-N7yOOLn3h8AIF0-UhysqN3WjZAr-rHGVkWmPVh2FS9s-bUcL7Il1q7IQ';
//        $openid = 'o5ZGIxPWrZBa61964QTRGkSWyUgo';
        $url = $this->_openUrlUserInfo.'?access_token='.$token.'&lang=zh-CN&openid='.$openid;
        return $this->httpGet($url);
    }

}